<template>
	<view id="body">
		<view class="navimg">
			<!-- 轮播图 -->
			<view class="u-demo-block">
				<u-swiper :list="goodsinfo.imglist" previousMargin="30" nextMargin="30" circular :autoplay="true"
					interval=4000 radius="5" bgColor="#ffffff"></u-swiper>
			</view>
		</view>
		<view class="order-price-sc">
			<view class="left-price">
				<text>￥</text>
				<text style="line-height: 56rpx;">{{goodsinfo.price}}</text>
			</view>
			<view class="right-sc" @click="toggleFavorite">
				<image v-if="goodsinfo.isFavorite" src="../static/img/collection.png" style="width: 40rpx;height: 40rpx;">
				</image>
				<image v-else src="../static/img/noCollection.png" style="width: 40rpx;height: 40rpx;"></image>
			</view>
		</view>
		<view class="order-conent">
			<view class="title">
				<text>商品名称:</text>
				<text style="margin-left: 24rpx;">{{goodsinfo.title}}</text>
			</view>
			<view class="content">
				<text>商品描述:</text>
				<text style="margin-left: 24rpx;">{{goodsinfo.content}}</text>
			</view>
			<view class="xt">
				<u-line color="#acacac"></u-line>
			</view>
			<view class="id">
				<text>商品编号:</text>
				<text style="margin-left: 24rpx;">{{goodsinfo.id}}</text>
			</view>
			<view class="xt">
				<u-line color="#acacac"></u-line>
			</view>
			<view class="type">
				<text>商品分类:</text>
				<text style="margin-left: 24rpx;">{{type[goodsinfo.type].name}}</text>
			</view>
			<view class="xt">
				<u-line color="#acacac"></u-line>
			</view>
			<view class="specifications">
				<text>规格:</text>
				<text style="margin-left: 24rpx;">{{goodsinfo.norms}}</text>
			</view>
			<view class="xt">
				<u-line color="#acacac"></u-line>
			</view>
			<view class="content">
				<text>商品数量:</text>
				<text style="margin-left: 24rpx;">{{goodsinfo.num}}</text>
			</view>
			<view class="xt">
				<u-line color="#acacac"></u-line>
			</view>
			<view class="sscolor">
				<text>保障:</text>
				<text style="margin-left: 24rpx;">运费险保障,破损包赔</text>
			</view>
			<view class="xt">
				<u-line color="#acacac"></u-line>
			</view>
			<view class="issusername">
				<text>卖家名称:</text>
				<text style="margin-left: 24rpx;">{{goodsinfo.issueUserName}}</text>
			</view>
			<view class="xt">
				<u-line color="#acacac"></u-line>
			</view>
		</view>
		<!-- 底部购物车 -->
		<view class="cart">
			<view class="xt">
				<u-line color="#acacac"></u-line>
			</view>
			<!-- 用户头像 -->
			<view class="issueUser" @click="contact" v-if="goodsinfo.state !=-1">
				<text class="t-icon t-icon-xiaoxi" style="width: 68rpx; height: 68rpx;"></text>
			</view>
			<!-- 加入购物车 -->
			<view class="addcart" @click="addcart"  v-if="goodsinfo.state !=-1">
				<text>加入购物车</text>
			</view>
			<!-- 立即购买 -->
			<view class="ljfk" @click="ljfk" v-if="goodsinfo.state !=-1">
				<text v-if="goodsinfo.state == 0">立即付款</text>
				<text v-if="goodsinfo.state == 1">立即购买</text>
			</view>
		</view>
		<!-- 购买数量模态框 -->
		<view class="nummodel">
			<u-modal :show="show" :showConfirmButton="false" :closeOnClickOverlay="true" @close="close">
				<view class="model">
					<!-- 数量 -->
					<view class="model-num">
						<text class="model-text">购买数量</text>
						<view class="num1">
							<u-number-box :max="goodsinfo.num" v-model="goodsinfo.buynum" @change="num1"></u-number-box>
						</view>
					</view>
					<view class="line" style="margin-top: 16rpx; padding-bottom: 16rpx;">
						<u-line color="#2979ff"></u-line>
					</view>
					<!-- 地址 -->
					<view class="v-name">
						<text class="t-icon t-icon-yonghu" style="width: 48rpx; height: 48rpx; float: left;"></text>
						<text class="mname">联系人</text>
						<input placeholder="输入姓名" class="name-input" v-model="name" />
					</view>
					<view class="line" style="margin-top: 64rpx;">
						<u-line color="#2979ff"></u-line>
					</view>
					<view class="v-phone">
						<text class="t-icon t-icon-shouji" style="width: 48rpx; height: 48rpx; float: left; "></text>
						<text class="mphone">联系电话</text>
						<input placeholder="输入电话" class="phone-input" v-model="phone" />
					</view>
					<view class="line" style="margin-top: 84rpx;">
						<u-line color="#2979ff"></u-line>
					</view>
					<view class="v-address">
						<text class="t-icon t-icon-dizhi" style="width: 48rpx; height: 48rpx; float: left; "></text>
						<text class="maddress">联系地址</text>
						<input placeholder="输入地址信息" class="address-input" v-model="address" />
					</view>
					<view class="line" style="margin-top: 84rpx;">
						<u-line color="#2979ff"></u-line>
					</view>
					<!-- 总价 -->
					<view class="totalprice">
						<text class="t-total">总价:</text>
						<text class="t-price">{{goodsinfo.buytotalprice}} 元</text>
					</view>
					<!-- 立即购买购买 -->
					<view class="buybutton" @click="buyclick">
						<text class="buybutton-text">立即购买</text>
					</view>
				</view>
			</u-modal>
		</view>
	</view>
</template>

<script>
	import {
		http
	} from "../static/service/requestAddress/rtas.js"
	import bignumber from "bignumber.js"
	export default {
		data() {
			return {
				//商品分类
				type: [{
						name: "禽畜肉类",
					},
					{
						name: "粮油米面",
					},
					{
						name: "水果",
					},
					{
						name: "蔬菜",
					},
					{
						name: "水产品",
					},
					{
						name: "其他",
					},
				],
				show: false,
				goodsinfo: {
					id: "", //商品id
					imglist: [], //商品图片信息
					type: 0, //商品类型
					price: "", //商品价格
					title: "", //商品标题
					content: "", //订单内容
					lodandnew: "", //新旧程度
					norms: "", //规格
					color: "", //颜色
					model: "", //型号
					issueUserName: "", //发布用户
					num: 0, //商品个数
					indeximg: "", //
					state: 0, //订单状态
					buynum: 1, //商品购买个数
					buytotalprice: 0, //订单总价
					isFavorite: false,
					module: "nongsuke",
				},
				name: "", //联系人姓名
				phone: "", //联系人
				address: "", //地址信息
				strimgList: "", //传递过来的订单图片字符串
			}
		},
		methods: {
			onLoad(options) { //页面接收信息
			if(options.data.length == 19){
							uni.request({
								url:http+"nongsuke/getnongsukeone/"+options.data,
								method:"GET",
								complete:(res)=>{
									if(res.data.code == 20021){
										var T = res.data.date
										if(T){
											var data = res.data.date
											this.goodsinfo = data
											this.strimgList = data.orderImg
											this.goodsinfo.imglist = data.orderImg.split(",") 
											this.goodsinfo.type = data.type -1
											this.goodsinfo.buytotalprice = data.price
										}else{
											uni.$u.toast("订单内容为空")
										}
									}else{
										uni.$u.toast("获取订单数据失败")
									}
								}
							})
						}else{
				console.log("接收的页面信息是:" + options.data)
				var data = JSON.parse(options.data)
				this.goodsinfo = data
				this.strimgList = data.orderImg
				this.goodsinfo.imglist = data.orderImg.split(",")
				this.goodsinfo.type = data.type - 1
				this.goodsinfo.buytotalprice = data.price
				}
				this.goodsinfo.module = "nongsuke"
				var userStr = uni.getStorageSync('user');
				var user = JSON.parse(userStr);
				const userId = user.id;
				// 使用商品ID作为唯一键加载isFavorite状态
				const favoriteKey = `isFavorite_${userId}_${this.goodsinfo.id}`;
				const storedIsFavorite = uni.getStorageSync(favoriteKey);
				this.goodsinfo.isFavorite = storedIsFavorite !== null ? storedIsFavorite : false;
			},
			// 添加收藏或取消收藏
			async toggleFavorite(index) {
				if(! uni.getStorageSync("user")){
					uni.$u.toast("登录后才能收藏喔")
					return
				}
				try {
					var userStr = uni.getStorageSync('user');
					var user = JSON.parse(userStr);
					const userId = user.id;
					// 使用商品ID作为唯一键
					const favoriteKey = `isFavorite_${userId}_${this.goodsinfo.id}`;
					// 查询当前商品是否已经被用户收藏
					const isFavoriteResponse = await uni.request({
						url: http + "favorites/check",
						method: "GET",
						data: {
							userId: userId,
							productId: this.goodsinfo.id,
						},
					});

					// 检查是否成功获取检查结果
					if (isFavoriteResponse && isFavoriteResponse[1].data) {
						if (this.goodsinfo.isFavorite) {
							// 商品已经被用户收藏，执行取消收藏操作
							const unfavoriteResponse = await uni.request({
								url: http + `favorites/remove/${userId}/${this.goodsinfo.id}`,
								method: "DELETE",
								data: {
									userId: userId,
									productId: this.goodsinfo.id,
								},
							});

							// 判断取消收藏的结果
							if (unfavoriteResponse && unfavoriteResponse[1].data.code === 20050) {
								// 取消收藏成功
								console.log('取消收藏成功', unfavoriteResponse[1]);
								this.goodsinfo.isFavorite = false;
								uni.removeStorageSync(favoriteKey);
							} else {
								console.log('取消收藏失败', unfavoriteResponse[1]);
								// 其他处理...
							}
						} else {
							// 商品未被用户收藏，执行收藏操作
							const favoriteResponse = await uni.request({
								url: http + "favorites/add",
								method: "POST",
								data: {
									userId: userId,
									productId: this.goodsinfo.id,
									favoriteTime: new Date().toISOString().slice(0, 19).replace("T", " "),
									module: this.goodsinfo.module,
									productTitle: this.goodsinfo.title,
									productImage: this.goodsinfo.imglist[0],
									productPrice: this.goodsinfo.price,
								},
							});

							// 判断收藏的结果
							if (favoriteResponse && favoriteResponse[1].data.code === 20060) {
								// 收藏成功
								console.log('收藏成功', favoriteResponse[1]);
								this.goodsinfo.isFavorite = true;
								uni.setStorageSync(favoriteKey, this.goodsinfo.isFavorite);
							} else {
								console.log('收藏失败', favoriteResponse[1]);
								// 其他处理...
							}
						}
						// 手动更新isFavorite值，触发视图更新
						this.$forceUpdate();
					} else {
						console.error('获取收藏状态失败，无效的响应格式', isFavoriteResponse);
					}
				} catch (error) {
					console.error('操作收藏失败', error);
					// 处理请求失败的情况
				}
			},

			//联系商家
			contact() {
				//添加用户到消息列表
				uni.navigateTo({
					url: "/see/chatpage" + "?id=" + this.goodsinfo.id + "&name=" + this.goodsinfo.issueUserName +
						"&img=" + this.goodsinfo.issueUserImg
				})
			},
			//添加购物车
			addcart() {
				uni.showLoading({
					title: "正在添加中",
					mask: true
				})
				if(! uni.getStorageSync("user")){
					uni.$u.toast("登录后才能添加购物车喔")
					return
				}else if(this.goodsinfo.num == 0){
					uni.$u.toast("数量为0，无法加入购物车")
					return
				}
				else{
				//获取缓存数组
				var list = uni.getStorageSync("cartlist")
				//缓存为空
				if (list == "") {
					var falg = []
					falg.push(this.goodsinfo)
					uni.setStorageSync("cartlist", JSON.stringify(falg))
					uni.$u.toast("添加购物车成功!")
				} else { //有数据的情况
					var falg = JSON.parse(list)
					//查询是否是重复商品
					for (var i = 0; i < falg.length; i++) {
						if (falg[i].id == this.goodsinfo.id) {
							//商品已经存在
							uni.$u.toast("商品已在购物车!")
							return
						}
					}
					//不存在的情况
					falg.push(this.goodsinfo)
					uni.setStorageSync("cartlist", JSON.stringify(falg))
					uni.$u.toast("添加购物车成功!")
				}
				}
			},
			ljfk() {
				if (!uni.getStorageSync("user")) {
					uni.$u.toast("登录后才能购买喔")
					return
				}
				this.show = true
			},
			//购买按钮
			buyclick() {
				let str = /^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$/;
				if(this.goodsinfo.buynum > this.goodsinfo.num){
					uni.$u.toast("购买数量不能大于商品数量")
				}
				else if(this.name == ""){
					uni.$u.toast("姓名不能为空")
					return
				}else if(this.phone == ""){
					uni.$u.toast("电话不能为空")
				}else if(str.test(this.phone) == false){
					uni.$u.toast("联系电话格式错误")
					return 
				}else if(this.address == ""){
					uni.$u.toast("地址不能为空")
					return 
				}else{
				var user = JSON.parse(uni.getStorageSync("user"))
				if(this.goodsinfo.buynum == undefined){
					this.goodsinfo.buynum = 1
				}
				var A = this.strimgList.split(",")
				// 封装订单内容对象
				var data = {
					id: "",
					title: this.goodsinfo.title,
					goodsid: this.goodsinfo.id,
					goodprice: this.goodsinfo.price,
					type: this.type + 1,
					buynum: this.goodsinfo.buynum,
					totalprice: this.goodsinfo.buytotalprice,
					state: 0,
					issuseuserid: user.id,
					imglist: this.strimgList,
					indeximg: A[0],
					belongid: "", //所属上级订单
				}
				var orli = []
				orli.push(data)
				//封装助农服务总订单表
				var nongsuke = {
					id: "",
					issueid: user.id,
					title: "助农服务商品订单:",
					orderlist: JSON.stringify(orli), //包含的内容订单id
					buyname: this.name,
					buyphone: this.phone,
					buyaddress: this.address,
					price: data.totalprice,
					state: 0
				}
				//创建订单数据
				var promise = new Promise(function(resolve, reject) {
					uni.request({
						url: http + "/nongsukellid",
						method: "POST",
						data: nongsuke,
						complete: (res) => {
							if (res.data.code == 20011) {
								uni.$u.toast("订单创建成功，快去付款吧")
								uni.navigateTo({
									url: "/shoppingcart/shoppingAllInfo?data=" + JSON
										.stringify(res.data.date)
								})
							} else {
								uni.$u.toast("订单创建失败!含有敏感词，请修改！")
							}
						}
					})
				})
				}
			},
			num1(e) {
				this.goodsinfo.buynum = e.value
				var num2 = bignumber(this.goodsinfo.price)
				this.goodsinfo.buytotalprice = num2.times(this.goodsinfo.buynum)
				this.$forceUpdate(this.goodsinfo)
			},
			close() {
				this.goodsinfo.buytotalprice = this.goodsinfo.price
				this.goodsinfo.buynum = 1
				this.show = false
			}
		
		}
	}
</script>
<style scoped>
	@import url("../static/css/componentsCss/nongsuke/nongsukeInfo.css");
</style>